package com.realbrand.net.realbrandpay.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.bean.VersionBean;
import com.realbrand.net.realbrandpay.db.DBManger;
import com.realbrand.net.realbrandpay.inter.IADS;
import com.realbrand.net.realbrandpay.inter.IVersion;
import com.realbrand.net.realbrandpay.ui.activity.login.LoginActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.api.HTTPAPI;
import com.realbrand.net.realbrandpay.untils.HttpRequest;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.weight.CircleProgressbar;
import com.realbrand.net.realbrandpay.weight.LocalCacheUtils;
import com.realbrand.net.realbrandpay.weight.MemoryCacheUtils;
import com.realbrand.net.realbrandpay.weight.NetCacheUtils;
import com.realbrand.net.realbrandpay.zxing.app.CaptureActivity;
import com.realbrand.net.realbrandpay.zxing.util.L;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/5/25.
 */

public class ADSActivity extends BaseActivity implements View.OnClickListener {
    @BindView(R.id.ads_progressBar)
    CircleProgressbar adsProgressBar;
    @BindView(R.id.ads_iv)
    ImageView adsIv;

    private String linkUrl;

    private String url;
    public static boolean aBoolean = true;
    //是否需要获取本地版本信息
    public static boolean isGetVersion = true;

    SharedPreferences sharedPreferences;

    private NetCacheUtils mNetCacheUtils;
    private LocalCacheUtils mLocalCacheUtils;
    private MemoryCacheUtils mMemoryCacheUtils;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        new DBManger(this).deleteSQL();
        adsProgressBar.setOutLineColor(Color.TRANSPARENT);
        adsProgressBar.setInCircleColor(Color.parseColor("#505559"));
        adsProgressBar.setProgressColor(Color.parseColor("#FF3030"));
        adsProgressBar.setProgressLineWidth(5);
        adsProgressBar.setProgressType(CircleProgressbar.ProgressType.COUNT);
        adsProgressBar.setTimeMillis(5000);
        adsProgressBar.reStart();
        adsProgressBar.setCountdownProgressListener(1, progressListener);
        sharedPreferences = getSharedPreferences(Constant.shareName, MODE_PRIVATE);
        String account = sharedPreferences.getString("account", "");
        long time = sharedPreferences.getLong("time", 0);
        //获取当前时间戳
        long l = Static.timeNow();
        long l1 = (l - time) / (1000 * 60 * 60);
        if (l1 >24) {
            LoginActivity.isLogin=false;
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.clear();
            edit.commit();
        }else {
            LoginActivity.isLogin = true;
        }
        mMemoryCacheUtils = new MemoryCacheUtils();
        mLocalCacheUtils = new LocalCacheUtils();
        mNetCacheUtils = new NetCacheUtils(mLocalCacheUtils, mMemoryCacheUtils);
        String urlPath = sharedPreferences.getString("url", "");
        Bitmap bitmapFromLocal = mLocalCacheUtils.getBitmapFromLocal(urlPath);
        if (bitmapFromLocal != null) {
            adsIv.setImageBitmap(bitmapFromLocal);
            L.d(L.TAG, "本地图片缓存" + bitmapFromLocal.toString());
        }
        getData();
        setOnClick();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ads_activity;
    }

    @Override
    protected void setOnClick() {
        adsProgressBar.setOnClickListener(this);
        adsIv.setOnClickListener(this);
    }


    public static final String VALUE_ADS = "adsActivity";

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ads_progressBar:
                Intent intent = new Intent(this, CaptureActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(Static.BundleKey, VALUE_ADS);
                intent.putExtras(bundle);
                startActivity(intent);
                adsProgressBar.stop();
                finish();
                break;
            case R.id.ads_iv:
                if (!linkUrl.equals("0")) {
                    Intent intentIv = new Intent();
                    intentIv.setData(Uri.parse(linkUrl));//Url 就是你要打开的网址
                    intentIv.setAction(Intent.ACTION_VIEW);
                    startActivity(intentIv); //启动浏览器
                    adsProgressBar.stop();
                }
                break;
        }

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Intent intent = new Intent(ADSActivity.this, CaptureActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(Static.BundleKey, VALUE_ADS);
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
    }

    private CircleProgressbar.OnCountdownProgressListener progressListener = new CircleProgressbar.OnCountdownProgressListener() {
        @Override
        public void onProgress(int what, int progress) {

            if (what == 1 && progress == 100) {
                Intent intent = new Intent(ADSActivity.this, CaptureActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString(Static.BundleKey, VALUE_ADS);
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
            }

        }
    };

    public void getData() {

        getImavige();
        getVersion();
        if (isGetVersion) {
            int appLocalVersion = Static.getAPPLocalVersion(ADSActivity.this);
            //保存本地版本号
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putInt(Constant.VersionBenDi, appLocalVersion);
            edit.putInt(Constant.VersionCompare, appLocalVersion);
            edit.commit();
        }

    }

    private void getVersion() {
        IVersion iVersion = HttpRequest.request_BASE_URL_VERSION(IVersion.class, HTTPAPI.BASE_URL_VERSION);
        iVersion.getVersion()
                .subscribeOn(Schedulers.newThread())//请求在新线程中执行
                .observeOn(Schedulers.io())//请求完成后再IO中执行
                .doOnNext(new Action1<VersionBean>() {
                    @Override
                    public void call(VersionBean versionBean) {
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//最后再主线程中执行
                .subscribe(new Subscriber<VersionBean>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(VersionBean versionBean) {
                        L.d(L.TAG, "版本信息" + versionBean.getVersionCode());
                        SharedPreferences.Editor edit = sharedPreferences.edit();
                        edit.putInt(Constant.VersionUpData, versionBean.getVersionCode());
                        edit.putString(Constant.VersionUpDataUrl, versionBean.getUrl());
                        edit.commit();
                        L.d(L.TAG, "下载地址" + versionBean.getUrl());
                    }
                });


    }

    private void getImavige() {
        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("METHOD", "Advertisement");
            jsonObject.put("SOURCE", "AdsActivity");
            jsonObject.put("CREDENTIALS", "0");
            jsonObject.put("TERMINAL", "0");
            jsonObject.put("INDEX", Static.getDay());
            jsonObject.put("DATA", 0);
            RequestBody body = RequestBody.create(HTTPAPI.JSON, jsonObject.toString());
            IADS iads = HttpRequest.request_BASE_URL(IADS.class);
            Call<ResponseBody> call = iads.advertisement(body);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String result = response.body().string();
                        if ("".equals(result)) {
                            Static.toast(ADSActivity.this, "网络繁忙");
                        } else {
                            L.d(L.TAG, "广告界面返回的结果" + result);
                            JSONObject resultJson = new JSONObject(result);
                            JSONArray data = resultJson.getJSONArray("DATA");
                            JSONObject object = data.getJSONObject(0);
                            url = object.getString("FilePosition");
                            linkUrl = object.getString("LinkPosition");
                            SharedPreferences.Editor edit = sharedPreferences.edit();
                            edit.putString("url", url);
                            edit.commit();
                            mNetCacheUtils.getBitmapFromNet(adsIv, url);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


}